package com.withmiku.world.user.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true) // 启用 @PreAuthorize 等注解
public class SecurityConfig {
    /**
     * 加密器 Bean —— 让 Spring 容器管理它，后续可以在 Service 中注入使用
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * Spring Security 过滤器链配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
        http
                // 关闭 CSRF（前后端分离）
                .csrf(AbstractHttpConfigurer::disable)

                // 设置为无状态会话
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))

                // 配置 URL 访问权限
                .authorizeHttpRequests(auth -> auth
                        // --- 放行 swagger ---
                        .requestMatchers(
                                "/swagger-ui/**",
                                "/swagger-ui.html",
                                "/v3/api-docs/**"
                        ).permitAll()

                        // --- 用户相关接口放行 ---
                        .requestMatchers(
                                "/api/user/login",
                                "/api/user/register"
                        ).permitAll()

                        // --- 头像访问等静态资源放行 ---
                        .requestMatchers("/uploads/**").permitAll()

                        // --- 管理员端口需要 ADMIN 角色 ---
                        .requestMatchers("/api/admin/**").hasRole("ADMIN")

                        // 放行logout，防止spring security默认机制禁止
                        .requestMatchers("/api/user/logout").permitAll()

                        // --- 其他请求都需要登录认证 ---
                        .anyRequest().authenticated()
                )
                // 把 JWT 过滤器加到 Spring Security 过滤链中
                // 在 Spring Security 处理认证前检查 token 合法性与封禁状态
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)

                // 禁用默认的登出机制（jwt模式不需要）
                .logout(AbstractHttpConfigurer::disable);

        return http.build();
    }
}
